using System;
using System.Collections;
using System.Data;
using System.Web.UI;
using System.Web.Profile;
using System.Web.Security;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System.Reflection;
using IWCommunity.Common;


namespace IWCommunity.UserRoleManagement
{
    /// <summary>
    /// Data source for the User Management user display view. Gets all FBA users and adds basic membership info 
    /// </summary>
    class FBAUsersView : DataSourceView
    {

        public FBAUsersView(IDataSource owner, string viewName) : base(owner, viewName) { }
        
        /// <summary>
        /// this is not the most efficient way of doing things, but works for now!!
        /// </summary>
        /// <param name="selectArgs"></param>
        /// <returns></returns>
        protected override IEnumerable ExecuteSelect(DataSourceSelectArguments selectArgs)
        {
            // only continue if a membership provider has been configured
            if (!Utilities.IsProviderConfigured())
                return null;

            // get site details
            SPSite site = SPContext.Current.Site;
            SPIisSettings settings = Utilities.GetFBAIisSettings(site);
            if (settings == null)
                return null;
            
            //SPWeb web = site.RootWeb;

            //// we only display users that have been added to SharePoint
            ////TODO:check if this is actually required
            //SPList list = web.Lists["User Information List"];

            //// create query list
            //SPQuery query = new SPQuery();
            //query.Query = string.Format(
            //    "<Where>" +
            //        "<And>" +
            //            "<Eq><FieldRef Name='ContentType' /><Value Type='Text'>Person</Value></Eq>" +
            //            "<BeginsWith><FieldRef Name='Name' /><Value Type='Text'>{0}</Value></BeginsWith>" +
            //        "</And>" +
            //    "</Where>" +
            //    "<OrderBy>" +
            //        "<FieldRef Name='LinkTitle' />" +
            //    "</OrderBy>", settings.MembershipProvider.ToString());

            //query.ViewFields = "<FieldRef Name='Name' /><FieldRef Name='LinkTitle' /><FieldRef Name='Email' /><FieldRef Name='Modified' /><FieldRef Name='Created' />";

            //// run query to get table of users
            //DataTable users = null;
            //try
            //{
            //    users = list.GetItems(query).GetDataTable();
            //}
            //catch (Exception ex) 
            //{
            //    Logger.LogError(ex);
            //    return null;
            //}
            //users.Columns.Add("Active");
            
            // Add additional user data to table
            //foreach (DataRow row in users.Rows)
            //{
            //    try
            //    {
            //        // remove provider name to get actual user name
            //        string userName = row["Name"].ToString().Replace(settings.MembershipProvider.ToLower() + ":", "");

            //        MembershipUser user = null;
            //        user = Membership.GetUser(userName);
            //        if (user != null)
            //        {
            //            row["Name"] = userName;
            //            row["Active"] = user.IsApproved ? "Yes" : "No";
            //        }
            //    }
            //    catch (Exception ex)
            //    {
            //        Logger.LogError(ex);
            //        return null;
            //    }
            //}

            DataTable usersTable = new DataTable(); ;
            usersTable.Columns.Add("name", typeof(string));
            usersTable.Columns.Add("email", typeof(string));
            usersTable.Columns.Add("title", typeof(string));
            usersTable.Columns.Add("active", typeof(string));
            usersTable.Columns.Add("modified", typeof(string));
            usersTable.Columns.Add("created", typeof(string));

            MembershipUserCollection users = Membership.GetAllUsers();
            foreach (MembershipUser user in users)
            {
                DataRow userRow = usersTable.NewRow();
                userRow["name"] = user.UserName;
                userRow["email"] = user.Email;
                userRow["active"] = user.IsApproved ? "Yes" : "No";
                userRow["created"] = user.CreationDate;
                userRow["modified"] = user.LastActivityDate;
                

                ProfileBase userProfile = DefaultProfile.Create(user.UserName);
                //note, even though we read a profile property here...the last activity is updated for a user
                //change the SP in the DB to stop this i.e. http://www.dotnet-friends.com/fastcode/sql/fastcodeinsqld7f4ebfa-dcc1-4f18-a073-3f3d10885207.aspx

                string fName = userProfile.GetPropertyValue("FirstName").ToString();
                string lName = userProfile.GetPropertyValue("LastName").ToString(); //, lastName);
                userRow["title"] = fName + " " + lName;

                usersTable.Rows.Add(userRow);
            }


         

            // sort if a sort expression available
            DataView dataView = new DataView(usersTable);

            string userFilter =  System.Web.HttpContext.Current.Request.QueryString["userFilter"];
            if (!string.IsNullOrEmpty(userFilter))
            {
                dataView.RowFilter = "name like '" + userFilter + "%'";

            }
            
            if (selectArgs.SortExpression != String.Empty)
            {
                dataView.Sort = selectArgs.SortExpression;
                
                
            }

            // return as a DataList            
            return (IEnumerable)dataView;
        }      
    }
}